/*
 * @Author: jiu yin
 * @Date: 2025-01-07 15:13:10
 * @FilePath: \node-socket-sersvice\src\utils\download.js
 * @LastEditTime: 2025-02-21 17:26:52
 * @LastEditors: jiu yin zhen jing
 */
const fs = require("fs");
const path = require("path");
const axios = require("axios");
let config = require("../../config");
const {rootPath}= require("../../utils.js");

async function downloadFile(url, fileName) {
	//   const fileName= path.basename(new URL(url).pathname)

	let downloadPath = path.join(rootPath, "./downloads");
	if (!fs.existsSync(downloadPath)) {
		fs.mkdirSync(downloadPath, { recursive: true });
	}
	let filePath = path.join(downloadPath, fileName);
	console.log("[ filePath ] >", filePath);
	try {
		let response = await axios.head(url); // 只获取头信息
		const totalSize = parseInt(response.headers["content-length"]);

		if (fs.existsSync(filePath) && checkFileStat(filePath, totalSize)) {
			console.log("[ 文件下载成功 getNewtUrl(fileName) ] >", getNewtUrl(fileName));
			return getNewtUrl(fileName);
		}


			// 检查写入权限
			try {
				fs.accessSync(rootPath, fs.constants.W_OK);
			} catch (error) {
				throw new Error(`没有写入权限: 请以管理员权限运行 ${rootPath}`);
			}

		response = await axios({
			method: "GET",
			url: url,
			responseType: "stream",
		});

	

		const writer = fs.createWriteStream(filePath);

		// 添加错误处理
		response.data.on("error", err => {
			console.error("下载流错误:", err);
			writer.end();
			clearFile(filePath);
		});
		// 添加中断处理
		writer.on("close", () => {
			if (!checkFileStat(filePath, totalSize)) {
				console.error("下载中断，文件不完整");
				clearFile(filePath); // 删除不完整的文件
				throw new Error("下载中断");
			}
		});
		response.data.pipe(writer);
		// 可以监听下载进度
		let downloaded = 0;
		response.data.on("data", chunk => {
			downloaded += chunk.length;
			console.log(`已下载: ${downloaded / 1024 / 1024} M/总:${totalSize / 1024 / 1024} M`);
		});
		return new Promise((resolve, reject) => {
			writer.on("finish", () => {
				// 再次验证文件完整性
				if (checkFileStat(filePath, totalSize)) {
					console.log("文件下载成功:", getNewtUrl(fileName));
					resolve(getNewtUrl(fileName));
				} else {
					const error = new Error("文件下载不完整");
					clearFile(filePath);
					reject(error);
				}
			});
			writer.on("error", err => {
				console.error("写入流错误:", err);
				writer.end();
				clearFile(filePath);
				reject(err);
			});
		});
	} catch (error) {
		console.error("下载文件失败:", error);
		throw error;
	}
}

function clearFile(filePath) {
	if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
}

function getNewtUrl(fileName) {
	return `http://${config.SERVER_IP}:${config.PORT}/downloads/${fileName}`;
}

// 再次验证文件完整性
function checkFileStat(filePath, totalSize) {
	const stats = fs.statSync(filePath);
	if (totalSize && stats.size < totalSize) return false;
	return true;
}

// downloadFile("https://resourcetest.aicverse.com/common/storage/8849f7b3-54b3-40d7-96e9-b0d3b5b191dd.apk", "8849f7b3-54b3-40d7-96e9-b0d3b5b191dd.apk");

module.exports = {
	downloadFile,
};
